package com.fzrskj.cloud.free.user.utils.func;

import com.fzrskj.cloud.free.core.enums.CartTypeEnum;
import com.fzrskj.cloud.free.core.enums.ProductTypeEnum;
import com.fzrskj.cloud.free.sys.bean.SysProductView;
import com.fzrskj.cloud.free.sys.utils.SysProductPriceUtils;
import com.fzrskj.cloud.free.user.bean.UserAccount;
import com.fzrskj.cloud.free.user.bean.UserAccountDetail;
import com.fzrskj.cloud.free.user.dao.UserAccountDao;
import com.fzrskj.cloud.free.user.dao.UserAccountDetailDao;
import com.fzrskj.cloud.free.user.dao.vo.AgentFinancePriceVo;
import com.fzrskj.cloud.free.user.dao.vo.AgentFinanceResultVo;
import com.fzrskj.cloud.free.user.utils.FuncHandleUtils;
import com.fzrskj.cloud.free.user.utils.UserAccountDetailUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountDetailView;
import com.fzrskj.cloud.free.user.bean.UserOrder;
import com.fzrskj.cloud.free.user.utils.UserLogUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * FuncHandleUtisAgentHelper.
 *
 * @author zj.
 *         Created on 2019/8/22 0022.
 */
public class FuncHandleUtisAgentHelper {
    /**
     * 订单对应的代理扣款.
     * @param userOrder
     * @param productView
     * @param thisAgentId
     * @return
     */
    public static AgentFinanceResultVo agentOrderPay(UserOrder userOrder, SysProductView productView, Integer thisAgentId) {
        AgentFinanceResultVo resultVo = new AgentFinanceResultVo();

        if (thisAgentId < 1) {
            resultVo.setResult(true);
            resultVo.setMessage("已到顶级平台");
            return resultVo;
        }
        //获取代理信息
        UserAccountDao accountDao = new UserAccountDao();
        UserAccount accountAgent = accountDao.getUserAccountWithoutAgent(thisAgentId);

        //判断当代理是否已支付。
        Map<String, Object> payCheck = new HashedMap();
        payCheck.put("status", 1);
        payCheck.put("userId", thisAgentId);
        payCheck.put("voucherId", userOrder.getOrderId());
        UserAccountDetailDao detailDao = new UserAccountDetailDao();
        UserAccountDetailView view = detailDao.queryUadViewWithoutAgentId(payCheck);

        if (null == view) {
            //获取代理应扣价格
            AgentFinancePriceVo priceVo = new AgentFinancePriceVo();
            //todo:补充所有产品类型注册价格获取.
            switch (userOrder.getProductClass()) {
                case "diy":
                    priceVo = getDiyAgentPrice(userOrder, accountAgent);
                    break;
            }

            if (null == priceVo || priceVo.getAmount() < 0) {
                return resultVo;
            }

            //订单类型
            String orderType="";
            if("add".equals(userOrder.getOrderType())) {
                orderType = "开通";
            } else if("renew".equals(userOrder.getOrderType())) {
                orderType = "续费";
            } else if("delete".equals(userOrder.getOrderType())) {
                orderType = "删除";
            } else if("update".equals(userOrder.getOrderType())) {
                orderType = "升级";
            }

            String financeDesc="";
            JSONObject param= JSONObject.fromObject(userOrder.getOrderParam());
            if(param.has("financeDesc")) {
                financeDesc = param.getString("financeDesc");
            } else {
                financeDesc = orderType;
            }

            //扣款并生成记账数据
            String remark="会员【"+userOrder.getUserName()+"】"+financeDesc+"产品【"+productView.getProductName()+
                    "】，订单号：【"+userOrder.getOrderId()+"】，代理【" + thisAgentId + "-" + accountAgent.getUserName() +
                    "】扣款【"+priceVo.getAmount()+"】";
            resultVo = financeAccount(accountAgent,300,remark,userOrder.getOrderId(),"","", priceVo.getAmount());
        } else {
            resultVo.setResult(true);
            resultVo.setMessage("已支付");
        }

        //检查是否向上检查代理扣款
        if (accountAgent.getAgentId() > 0) {
            return agentOrderPay(userOrder, productView, accountAgent.getAgentId());
        }

        return resultVo;
    }

    /**
     * 获取代理商域名成本价.
     * @param userOrder 用户订单.
     * @param accountAgent 代理商账号.
     * @return 价格信息.
     */
    public static AgentFinancePriceVo getDomainAgentPrice(UserOrder userOrder, UserAccount accountAgent) {
        Map<String,Object> cdt = new HashMap<String, Object>();
        cdt.put("productCode", userOrder.getProductCode());
        cdt.put("levelCode", accountAgent.getLevelCode());

        AgentFinancePriceVo priceVo = new AgentFinancePriceVo();

        //注册/续费
        if(CartTypeEnum.ADD.equals(userOrder.getOrderType())) {
            cdt.put("chargeId", 1);
        } else if(CartTypeEnum.RENEW.equals(userOrder.getOrderType())) {
            cdt.put("chargeId", 2);
        } else {
            //其他操作不需要费用
            priceVo.setAmount(0.0);
            priceVo.setMessage("该操作免费");
        }

        cdt.put("regType", userOrder.getRegType());
        cdt.put("productClass", userOrder.getProductClass());
        cdt.put("agentId", accountAgent.getAgentId());

        SysProductPriceUtils sppUtils = new SysProductPriceUtils();
        Integer price = sppUtils.getDomainProductPrice(userOrder.getApplyTime(), cdt);

        if (price > 0) {
            priceVo.setAmount(price.doubleValue());
            priceVo.setMessage("获取价格成功");
        }
        return priceVo;
    }

    public static AgentFinancePriceVo getDiyAgentPrice(UserOrder userOrder, UserAccount accountAgent) {
        AgentFinancePriceVo priceVo = new AgentFinancePriceVo();
        priceVo.setAmount(-1.0);
        priceVo.setMessage("不支持的注册商");
        if (ProductTypeEnum.DIY.getTag().equals(userOrder.getRegType())) {
            priceVo = FuncHandlePriceVitrualDiyHelper.getPrice(userOrder, accountAgent);
        }
        return priceVo;
    }

    /**
     * 财务记账,
     * @param account
     * @param itemId
     * @param remark
     * @param voucherId
     * @param bankCode
     * @param billno
     * @param amount
     * @return
     */
    public static AgentFinanceResultVo financeAccount(UserAccount account, int itemId,String remark,String voucherId,String bankCode,String billno,double amount){
        AgentFinanceResultVo resultVo = new AgentFinanceResultVo();
        if(amount<0){
            resultVo.setMessage("发生金额不能为负数");
            return resultVo;
        }

        synchronized(FuncHandleUtils.class){
            if(itemId==200 || itemId==300){
                if(account.getBalance()<amount){
                    resultVo.setMessage("操作失败，余额不足");
                    return resultVo;
                }
            }

            double balance = account.getBalance();
            switch(itemId){
                case 100:
                    balance+=amount;
                    break;
                case 200:
                    balance-=amount;
                    break;
                case 300:
                    balance-=amount;
                    break;
                case 400:
                    balance+=amount;
                    break;
                case 500:
                    balance+=amount;
                    break;
                case 600:
                    balance-=amount;
                    break;
            }

            if(balance<0) {
                balance = 0;
            }

            UserAccountDao userAccountDao = new UserAccountDao();
            int ret=userAccountDao.updateBlanceWithoutAgent(account.getUserId(), account.getUserName(), balance);
            if(ret>0){
                //插入记账数据
                UserAccountDetail entity = new UserAccountDetail();
                entity.setSnId("SN"+String.valueOf((new Date()).getTime()));
                entity.setUserId(account.getUserId());
                entity.setUserName(account.getUserName());
                entity.setItemId(itemId);
                entity.setRemark(remark);
                entity.setVoucherId(voucherId);
                entity.setBankCode(bankCode);
                entity.setBillno(billno);
                entity.setAmount(amount);
                entity.setBalance(balance);
                entity.setOperator(account.getUserName());
                entity.setRegDate(new Date());
                entity.setStatus(1);
                entity.setAgentId(account.getAgentId());

                UserAccountDetailUtils uadUtils=new UserAccountDetailUtils();
                ret=uadUtils.addUserAccountDetail(entity);
                if(ret>0){
                    resultVo.setResult(true);
                    resultVo.setMessage("操作成功");
                }
            }else{
                resultVo.setMessage("记账失败");
                UserLogUtils.addLog(FuncHandleUtisAgentHelper.class, account.getUserId(),
                        "请求参数：金额["+amount+"]，用户名["+account.getUserName()+"]，记账项["+itemId+"]");
            }
        }

        return resultVo;
    }
}
